package com.kern.utils;

import com.kern.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by caoshi at 12:00 2021-07-18
 */
public class HtmlParseUtil {

    public static List<Content> getDataFromHtml(String keyWords) throws IOException {
        List<Content> contents = new ArrayList<>();

        String url = "https://search.jd.com/Search?keyword=" + keyWords;
        Document document = Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows NT 5.1; zh-CN) AppleWebKit/535.12 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/535.12")
                .timeout(30000).get();

        Element ele = document.getElementById("J_goodsList");
        Elements li = ele.getElementsByTag("li");

        for (int i = 0; i < li.size(); i++) {
            Element el = li.get(i);
            Content content = new Content();
            String imgSrc = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();
            content.setImg(imgSrc);
            content.setPrice(price);
            content.setTitle(title);
            contents.add(content);
            System.out.println("============================================");
            System.out.println(content);
        }

        return contents;
    }


    public static void main(String[] args) throws IOException {

        getDataFromHtml("Java");

    }


}
